﻿#encoding: utf-8

require 'pexels'
require 'open-uri'

load 'tutem_utils.rb'
load 'wechat_api.rb'

def calc_sawn_bonus reader_count, new_readers

  return 0 if reader_count < 1

  base = ( 1 + new_readers ) * 10 + reader_count

  reader_count.times do |i|
    a = 1
    a = 2 if i < 8
    a = 3 if i < 4
    a = 4 if i < 2
    base += a
  end

  base = 200 if base > 200
  return base

end

def shared_users_during start_time, end_time

  #获得准备发放积分的所有用户
  users = {}
  #所有该时段分享过的用户
  sql = "select a.uid, sum(a.times) as shared_times, u.real_name as real_name , u.promoter_type, u.integral as p_balance, w.openid, w.subscribe from tutem_mall.eb_user_action a left join tutem_mall.eb_user u on (a.uid = u.uid) left join tutem_mall.eb_wechat_user w on (a.uid = w.uid)  where a.action = 'share' and a.uid != a.peer_uid and a.add_time >= #{start_time} and a.add_time < #{end_time} group by a.uid"
  (queryRds(sql)).each do |q|
    user = {}
    uid = q['uid']
    user.store 'uid', uid
    user.store 'shared_times', q['shared_times']
    user.store 'real_name', q['real_name']
    user.store 'p_balance', q['p_balance']
    user.store 'openid', q['openid']
    user.store 'promoter_type', q['promoter_type']
    user.store 'subscribe', q['subscribe']
    users.store uid, user
  end
  #补充该时段被阅读过分享的用户
  sql = "select a.peer_uid, u.real_name as real_name, u.integral as p_balance, w.openid, w.subscribe from tutem_mall.eb_user_action a left join tutem_mall.eb_user u on (a.peer_uid = u.uid) left join tutem_mall.eb_wechat_user w on (a.peer_uid = w.uid) where a.action = 'open' and a.peer_uid !=0 and a.uid!= a.peer_uid and a.add_time >= #{start_time} and a.add_time < #{end_time} group by a.peer_uid"
  (queryRds(sql)).each do |q|
    uid = q['peer_uid']
    if users[uid].nil?
      user = {}
      user.store 'uid', uid
      user.store 'shared_times', 0
      user.store 'real_name', q['real_name']
      user.store 'p_balance', q['p_balance']
      user.store 'openid', q['openid']
      user.store 'subscribe', q['subscribe']
      users.store uid, user
    end
  end

  return users

end

def daily_shared_users day

  start_time = Time.parse(day.to_s + " 00:00:00").to_i
  end_time  = Time.parse(day.next_day.to_s + " 00:00:00").to_i
  return shared_users_during start_time, end_time

end

def daily_shared_recs day

  code = "SHR-#{day}"

  start_time = Time.parse(day.to_s + " 00:00:00").to_i
  end_time  = Time.parse(day.next_day.to_s + " 00:00:00").to_i

  #提前准备当天新增加用户名单
  sql = "select a.uid as uid from tutem_mall.eb_user_action a left join tutem_mall.eb_user u on (a.uid = u.uid) where action = 'open' and a.add_time >= #{start_time} and a.add_time < #{end_time} and u.add_time >= #{start_time} and u.add_time < #{end_time} group by a.uid;"
  new_uids = []
  (queryRds(sql)).each { |q| new_uids += [q['uid']] }

  #符合计算积分条件的用户
  users = daily_shared_users day

  #准备积分发放数据
  recs = []
  users.each do |uid, user|

    rec = {}
    rec.store 'uid', user['uid']

    real_name = user['real_name']
    real_name = '未注册' if real_name.to_s.empty?
    rec.store 'real_name', real_name

    shared_times = user['shared_times']
    rec.store 'shared_times', shared_times
    shared_bonus = shared_times > 0 ? 10 : 0
    rec.store 'shared_bonus', shared_bonus

    sq2 = "select uid, sum(times) as read_times from tutem_mall.eb_user_action where peer_uid = #{uid} and uid != peer_uid and action = 'open' and add_time >= #{start_time} and add_time < #{end_time} group by uid;"
    readers = []
    reader_count = 0
    read_times = 0
    new_readers = 0

    (queryRds(sq2)).each do |r|
      readers += [r['uid']]
      reader_count += 1
      new_readers += 1 if (new_uids.include? r['uid'])
      read_times += r['read_times']
    end

    #rec.store 'readers', readers
    rec.store 'reader_count', reader_count
    rec.store 'read_times', read_times
    rec.store 'new_readers', new_readers

    sawn_bonus = calc_sawn_bonus reader_count, new_readers
    rec.store 'sawn_bonus', sawn_bonus

    bonus = rec['sawn_bonus'] + rec['shared_bonus']
    rec.store 'bonus', bonus

    title = "#{code} 转发#{shared_times} 被读#{read_times} 读者#{reader_count} 新人#{new_readers}"
    brief = "转发#{shared_times} 被读#{read_times} 读者#{reader_count} 新人#{new_readers}"
    rec.store 'title', title
    rec.store 'code', code
    rec.store 'brief', brief

    recs += [rec]

  end

  recs = recs.sort_by { |p| p['bonus'] }
  recs = recs.reverse
  return recs

end

def incentive_daily_share

  day = Date.today.prev_day
  code = "SHR-#{day}"

  users = daily_shared_users day #{}
  recs = daily_shared_recs day   #[]

  recs.each do |rec|

    uid = rec['uid']
    title = rec['title']
    bonus = rec['bonus']
    brief = rec['brief']

    incentived = 0
    sql = "select count(*) as incentived from tutem_mall.eb_user_bill where uid = #{uid} and link_id = '#{code}'"
    (queryRds(sql)).each do |q|
      incentived = q['incentived']
      break
    end

    next if incentived > 0
    #puts "incentive #{uid} with #{bonus} for #{title}"

    user = users[uid]
    subscribe = user['subscribe']
    if subscribe == 1 && user['promoter_type'] != 1
        openid = user['openid']
        balance = user['p_balance'] + bonus
        totem_points_change_notice  openid, "#{code} 分享获赠积分", bonus
    else
        #通知用户关注微信公众号后激活
    end

    sqls = []

    sqls += [ "update tutem_mall.eb_user set integral = integral + #{bonus} where uid = #{uid};" ]
    usql = "INSERT INTO tutem_mall.eb_user_bill (`uid`, `link_id`, `pm`, `title`, `category`, `type`, `number`, `balance`, `mark`, `add_time`, `status`, `take`) 
      SELECT #{uid}, '#{code}', 1, '#{title}', 'integral', 'system_add', #{bonus}, integral, '#{title}', #{Time.now.to_i}, 1, 0 from tutem_mall.eb_user where uid = #{uid}"
    sqls += [usql]

    commitTrans sqls

  end

end

def report_daily_share

    day = Date.today.prev_day
    title = "SHR-#{day}转发汇总"
    group_size = 50

    users = daily_shared_users day
    recs = daily_shared_recs day

    recs_group = recs.each_slice(group_size).to_a #太长发不了
    idx = 1
    recs_group.each do |recs|
      report_daily_share_ "#{title}#{idx}", recs, users
      idx += 1
    end

end

def report_daily_share_ title, recs, users

    mark_down = "# #{title}\n"
    mark_down += " USERS:#{recs.size} YBONUS\n\n"

    ybonus = 0
    recs.each do |rec|
      uid = rec['uid']
      user = users[uid]
      ybonus += rec['bonus']
      mark_down += "**[#{sprintf("%05d",uid)}] #{rec['real_name']} +#{rec['bonus']} #{user['subscribe']==0?'x':''}**\n"
      mark_down += " #{rec['brief']}\n"
    end
    mark_down += "\n"
    mark_down += ">#{Time.at(Time.now)}\n"

    mark_down = mark_down.gsub 'YBONUS', 'BONUS:' + ybonus.to_s

    send_message_to_bot 'WWBOT_XT', mark_down, ['@all']
    return mark_down

end

#就算每天的分享积分
incentive_daily_share
report_daily_share
